package com.xyz.messagehelper.presenter

import android.content.IntentFilter
import com.xyz.messagehelper.SendMessageRunnable
import com.xyz.messagehelper.bean.ConstantValue
import com.xyz.messagehelper.bean.MessageEvent
import com.xyz.messagehelper.broad_cast_reciver.SMSReceiver
import com.xyz.messagehelper.contract.SendMessageTaskContract
import com.xyz.messagehelper.utils.SharePreferenceUtils
import com.xyz.messagehelper.utils.Utils
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.io.File
import java.io.FileReader
import java.io.LineNumberReader

class SendMessageTaskPresenter(var mView: SendMessageTaskContract.View) :
    SendMessageTaskContract.Presenter {
    private var sendActionBroadcast: SMSReceiver? = null

    private var messageTotalCount = 0;
    private var sendMessageSuccessCount = 0;
    private var sendMessageFailCount = 0;
    private var alreadySendMessageCount = 0

    private val sendMessageRunnable: SendMessageRunnable = SendMessageRunnable();

    override fun onDestoryPresenter() {
        destorySendMessageTask()
        mView == null
        EventBus.getDefault().unregister(this)
        if (sendActionBroadcast != null) {
            Utils.context.unregisterReceiver(sendActionBroadcast)
        }
    }


    private fun initBroadCast() {
        val mFilter = IntentFilter(ConstantValue.SMS_SEND_ACTIOIN)
        mFilter.addAction(ConstantValue.SMS_DELIVERED_ACTION)
        sendActionBroadcast = SMSReceiver()
        Utils.context.registerReceiver(sendActionBroadcast, mFilter)
    }

    override fun initPresenter() {
        EventBus.getDefault().register(this)
        initBroadCast()
        Thread {
            val path: String? = SharePreferenceUtils.getString(Utils.context, "message_path", null)
            val messageRules: String? =
                SharePreferenceUtils.getString(Utils.context, "message_rules", null)
            if (path == null || messageRules == null) return@Thread
            val file = File(path)
            val numberLinesReader = LineNumberReader(FileReader(file))
            numberLinesReader.skip(file.length())
            messageTotalCount = numberLinesReader.lineNumber + 1;


            val it = file.readLines()[0]
            val strArray = it.split(",")
            val length = strArray.size

            var messageContent: String = messageRules

            if (messageRules.contains("{date}")) {
                messageContent = messageContent.replace("{date}", Utils.getDate())
            }

            if (messageRules.contains("{time}")) {
                messageContent = messageContent.replace("{time}", Utils.getTime())
            }

            if (messageRules.contains("{var1}") && length >= 2) {
                messageContent = messageContent.replace("{var1}", strArray[1])
            }

            if (messageRules.contains("{var2}") && length >= 3) {
                messageContent = messageContent.replace("{var2}", strArray[2])
            }

            if (messageRules.contains("{var3}") && length >= 4) {
                messageContent = messageContent.replace("{var3}", strArray[3])
            }
            runUiThread {
                if (mView == null) return@runUiThread
                mView.showMessageTotalCount(messageTotalCount)
                mView.showMessageTemplate(messageContent)
            }
        }.start()
    }


    override fun startSendMessageTask() {
        messageTotalCount = 0
        sendMessageFailCount = 0
        sendMessageSuccessCount = 0
        alreadySendMessageCount = 0
        sendMessageRunnable.startTask()
        Thread(sendMessageRunnable).start()
        mView.startSendMessageTask("开始发送短信任务")
        mView.showRunningRemindInfo("任务正在运行...")
    }

    override fun pauseSendMessageTask() {
        if (sendMessageRunnable.pauseTask(true)) {
            mView.showRemindTost("暂停成功")
            mView.pauseSendMessageTask("任务已暂停")
            mView.showRunningRemindInfo("任务已暂停")
        }
    }

    override fun resumeSendMessageTask() {
        sendMessageRunnable.pauseTask(false)
        mView.resumeSendMessageTask("任务已恢复")
    }

    override fun destorySendMessageTask() {
        sendMessageRunnable.destoryTask()
        mView.destorySendMessageTask("任务已结束")
    }


    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEvent(event: MessageEvent) {
        when (event.flag) {
            ConstantValue.START_SEND_TASK_FAIL -> {
                mView.remindNoChoicePath("开始发送短信任务失败")
            }
            ConstantValue.SEND_MESSAGE_TASK_COMPLETE -> {
                mView.destorySendMessageTask("任务已完成")
                mView.showRunningRemindInfo("任务已完成")
                destorySendMessageTask()
            }
            ConstantValue.SENT_MESSAGE_SUCCESS -> {
                sendMessageSuccessCount++
                mView.showSendSuccesMessageCount(sendMessageSuccessCount)
            }
            ConstantValue.SENT_MESSAGE_FAIL -> {
                sendMessageFailCount++
                mView.showFailMessageCount(sendMessageFailCount)
            }
            ConstantValue.SEND_MESSAGE -> {
                alreadySendMessageCount++
                mView.showSendMessageTaskSchedule(alreadySendMessageCount)
            }
        }
    }
}